package com.qf.shiro.util;

import java.sql.*;

public class JdbcUtil {

    private static final String USER = "root";
    private static final String PASSWORD = "zhu980510";
    private static final String URL = "jdbc:mysql://localhost:3306/shiro?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    private static Connection conn;  // 数据库连接
    private static PreparedStatement pstmt;
    private static ResultSet rs;  // 结果集
    public static void getCon(){

        try {
            Class.forName(DRIVER); // 加载驱动
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void closeAll(){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 封装的执行查询的方法
     * */
    public static ResultSet executeQuery(String sql,Object...params){
        getCon();

        try {
            pstmt = conn.prepareStatement(sql);

            if(pstmt!=null&&params.length>0){
                for(int i=0;i<params.length;i++){
                    pstmt.setObject(i+1,params[i]);
                }
            }

            rs = pstmt.executeQuery();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return rs;
    }

    public static int executeUpdate(String sql,Object...params) {
        getCon();
        int result = 0;
        try {
            pstmt = conn.prepareStatement(sql);
            if(pstmt!=null&&params.length>0){
                for(int i=0;i<params.length;i++){
                    pstmt.setObject(i+1,params[i]);
                }
            }

            result= pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return result;

    }



    public static void main(String[] args) {
        getCon();
        System.out.println(conn);
    }
}
